#include <stdio.h>

// 二分查找函数（数组必须有序）
int binary_search(int arr[], int size, int target)
{
    int left = 0;         // 左边界
    int right = size - 1; // 右边界

    while (left <= right)
    {                                        // 当搜索区间有效时继续
        int mid = left + (right - left) / 2; // 防止溢出的中间值计算

        if (arr[mid] == target)
        {               // 找到目标元素
            return mid; // 返回索引位置
        }
        else if (arr[mid] < target)
        {                   // 目标在右半区
            left = mid + 1; // 调整左边界
        }
        else
        {                    // 目标在左半区
            right = mid - 1; // 调整右边界
        }
    }
    return -1; // 未找到返回-1
}

int main()
{
    // 有序测试数组（必须升序排列）
    int data[] = {7, 12, 23, 45, 56, 67, 78, 89, 90, 100};
    int size = sizeof(data) / sizeof(data[0]);

    // 情况1：查找成功（中间值）
    int target1 = 56;
    int result1 = binary_search(data, size, target1);

    if (result1 != -1)
    {
        printf("Element %d found at index %d.\n", target1, result1); // 输出查找成功信息
    }
    else
    {
        printf("Element %d not found in the array.\n", target1);
    }

    // 情况2：查找成功（边界值）
    int target2 = 7;
    int result2 = binary_search(data, size, target2);

    if (result2 != -1)
    {
        printf("Element %d found at index %d.\n", target2, result2);
    }
    else
    {
        printf("Element %d not found in the array.\n", target2);
    }

    // 情况3：查找失败（值在范围内但不存在）
    int target3 = 55;
    int result3 = binary_search(data, size, target3);

    if (result3 != -1)
    {
        printf("Element %d found at index %d.\n", target3, result3);
    }
    else
    {
        printf("Element %d not found in the array.\n", target3); // 输出查找失败信息
    }

    // 情况4：查找失败（值超出范围）
    int target4 = 120;
    int result4 = binary_search(data, size, target4);

    if (result4 != -1)
    {
        printf("Element %d found at index %d.\n", target4, result4);
    }
    else
    {
        printf("Element %d not found in the array.\n", target4); // 输出查找失败信息
    }

    return 0;
}